<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button :disabled="!canSave" @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                :class="orderId ? '' : 'not-mongolia'"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择供应商"
              >
                <template #append>
                  <el-icon @click="_selectsupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品
              </el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品
              </el-button>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                :checkbox="true"
                :isRowClickSelect="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="scope.row.qtyOperateMode !== 3"
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="99999999"
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="changeSmall($event, scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!--选择产品-->
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :query-params="productInfo.query.queryParams"
      :table-key="productInfo.tableKey"
      :api="productInfo.api"
      :show-price="$permission('withTableKit:price')"
      @callback="selectProduct"
    />
    <!--选择供应商-->
    <select-supplier
      v-if="selectSupplierInfo.visible"
      v-model:show-dialog="selectSupplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :api="selectSupplierInfo.api"
      :query="selectSupplierInfo.query"
      @callback="selectSupplierCallback"
    />
    <AcceptOrderNo
      v-if="acceptOrderNoInfo.visible"
      v-model:show-dialog="acceptOrderNoInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :show-price="$permission('withTableKit:price')"
      :save-empty="true"
      @callback="selectAcceptOrderNoCallback"
    />
  </div>
</template>

<script setup name="withTableKitModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'

import {
  getWithTableKitById,
  getWithTableKitDetailAll,
  createWithTableKit,
  updateWithTableKit,
} from '@/api/withTable.js'
import {
  getCustomizeListWithAllSupplierList,
  getSupplierPage,
  getCoreCodeStatus,
} from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import AcceptOrderNo from '../components/acceptOrderNo'
import SelectSupplier from '@/components/SelectSupplier/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const NewSelectProduct = defineAsyncComponent(() =>
  import('@/components/NewSelectProduct/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const props = defineProps(['visible', 'title', 'orderId'])

const productionTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})

//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    supplierName: '',
    supplierId: '',
  },
  fieldList: [
    {
      label: '手术包名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '手术包编码',
      value: 'code',
      type: 'input',
      show: false,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入手术包名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入手术包编码', trigger: 'blur' }],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'scanCode' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
let productInfo = reactive({
  visible: false,
  api: getCustomizeListWithAllSupplierList,
  tableKey:
    'withTableKitProductPage-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      withOperateTable: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
    queryParams: {},
  },
})

const selectSupplierInfo = reactive({
  visible: false,
  index: '',
  api: getSupplierPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const acceptOrderNoInfo = reactive({
  visible: false,
})
const formRefs = ref('')
const btnLoading = ref(true)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return formInfo.data.supplierId && formInfo.data.supplierId
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, parseFloat(row.price)),
        unitConvertCoefficient
      )
    })
  },
  {
    deep: true,
  }
)

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableKit:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableKit:price'),
    hidden: true,
  },
  defaultSupplierName: {
    label: '默认供应商',
    value: 'defaultSupplierName',
    type: 'column',
    hidden: true,
  },
  defaultSupplierCode: {
    label: '默认供应商编码',
    value: 'defaultSupplierCode',
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableKit:price'),
    hidden: true,
  },
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getStatus()

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}
function getList() {
  getWithTableKitDetailAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
    case 'changePrice':
      proxy.$refs.tableForm.clearValidate(data)
      break
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let notQtyDetails = tableInfo.data
      .filter((row) => !row.qty)
      .map((item) => item.productCode)
    if (notQtyDetails.length) {
      proxy.$message({
        message: `请填写产品编码为【${notQtyDetails}】的产品数量`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let data = formInfo.data
    data.mergeDetails = tableInfo.data
    const api = props.orderId ? updateWithTableKit : createWithTableKit
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}

//选择供应商
function _selectsupplier() {
  if (!props.orderId) {
    selectSupplierInfo.visible = true
    selectSupplierInfo.query.supplierIdNotIn = formInfo.data.supplierId
  }
}
function selectSupplierCallback(data = undefined) {
  if (data && data.supplierId) {
    formInfo.data.supplierId = data.supplierId
    formInfo.data.supplierName = data.supplierName
    productInfo.query.queryMap.supplierId.value = data.supplierId
    tableInfo.data = []
  } else {
    formInfo.data.supplierId = ''
    formInfo.data.supplierName = ''
    productInfo.query.queryMap.supplierId.value = ''
    tableInfo.data = []
  }
}
function selectAcceptOrderNo() {
  acceptOrderNoInfo.visible = true
}
function selectAcceptOrderNoCallback(data) {
  if (data && data.supplierId) {
    formInfo.data.acceptOrderNo = data.orderNo
    formInfo.data.acceptOrderId = data.id
    tableInfo.data = []
  } else {
    formInfo.data.acceptOrderNo = ''
    formInfo.data.acceptOrderNo = ''
    tableInfo.data = []
  }
}
//选择产品
function addProduct() {
  const productIds = tableInfo.data.map((item) => item.productId)
  productInfo.query.queryMap.id.value = productIds.toString()
  productInfo.visible = true
}
function selectProduct(rows = []) {
  if (rows.length) {
    tableInfo.data = rows.concat(tableInfo.data)
  }
}

//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice && row.codeType === 3) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'withTableKitModify-com.slip.spd.entity.vo.withtable.WithTableKitDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.orderId) {
        getMain()
      }
    }
  })
}
function getMain() {
  getWithTableKitById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      productInfo.query.queryMap.supplierId.value = res.data.supplierId
      filterInfo.query.queryMap.orderId.value = props.orderId
      getList()
    }
  })
}
function getStatus() {
  getCoreCodeStatus({ codeType: '12' }).then((res) => {
    showFieldListItem(!res.data, 'code')
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
</script>
